package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/18 23:00
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    
    @Resource
    CourseCategoryMapper courseCategoryMapper;


    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        // 调用mapper递归查询出分类信息
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        
        // 找到每个节点的子节点 封装成List<CourseCategoryTreeDto>
        // 先将list转成map，key就是节点的id，value就是CourseCategoryTreeDto
        // filter排除根节点
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().filter(item -> 
                !id.equals(item.getId())).collect(Collectors.toMap(key ->
                key.getId(), value -> value, (key1, key2) -> key2)
        );
        // 定义一个list作为最终返回的list
        List<CourseCategoryTreeDto> courseCategoryTreeDtoList = new ArrayList<>();
        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item -> {
            if (item.getParentid().equals(id)){
                courseCategoryTreeDtoList.add(item);
            }
            // 找到每个节点的子节点放在父节点的childrenTreeNodes中
            CourseCategoryTreeDto courseCategoryTreeParent = mapTemp.get(item.getParentid());
            if (courseCategoryTreeParent != null){
                if (courseCategoryTreeParent.getChildrenTreeNodes() == null){
                    // 如果改父节点的ChildreTreeNodes属性为空要new一个集合，因为要向该集合中放它的子节点
                    courseCategoryTreeParent.setChildrenTreeNodes(new ArrayList<>());
                }
                courseCategoryTreeParent.getChildrenTreeNodes().add(item);
            }
            
        });
        
        

        // 从头遍历 List<CourseCategoryTreeDto>，一边遍历一边找子节点放在父节点的childrenTreeNodes
        return courseCategoryTreeDtoList;
    }
}
